import ajax from '../../ajax'
import { Source } from '../../ajax'
import changeProps from '../changeProps'
import { mixinBeforeReqData } from '../mixins'

export default function(Route){

  if(!Route.beforeRequest.url)
    return false

  let props = Route.props
  let resData = {beforeData: null}

  const beforeEnter = Route.beforeEnter || null
  const mixins = Route.component.mixins || []

  Route.props = changeProps(props, resData)

  Route.component.mixins = mixinBeforeReqData(mixins)

  Route.beforeEnter = (to, from, next) => {
    const beforeRequest = status => {

      if(status !== undefined)
        return next(status)

      const url = Route.beforeRequest.url
      const type = Route.beforeRequest.type || 'get'
      const data = Route.beforeRequest.data
      const response = Route.beforeRequest.response
      const source = Source()

      const nexts = function(status){
        $loading.hide().then(() => {
          if(status instanceof Error)
            $toast.show(status.message)

          next(status)
        })
      }

      $loading.show('拼命加载中..')
      .then(() => {
        return {
          url,
          type,
          data,
          source
        }
      })
      .then(ajax)
      .then(res => {
        resData.beforeData = res.data
        response.call(res, null, resData, nexts)
      })
      .catch(err => {
        resData.beforeData = err
        response.call(err.response || window, err, resData, nexts)
      })

    }
    if(typeof beforeEnter === 'function')
      beforeEnter(to, from, beforeRequest)
    else beforeRequest()
  }

}
